﻿using System;
using System.IO;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Microsoft.Win32;
using SHomeWorkshop.LunarConcept.Controls;
using SHomeWorkshop.LunarConcept.ModifingManager;
using SHomeWorkshop.LunarConcept.Tools;
using System.Collections.Generic;
using SHomeWorkshop.LunarConcept.Widgets.WidgetsStyleSamples;

namespace SHomeWorkshop.LunarConcept.Dialogs
{
    /// <summary>
    /// 创建时间：2011年12月31日
    /// 创建者：  杨震宇
    /// 
    /// 主要用途：DocumentOptionsDialog.xaml 的交互逻辑。
    ///           用于为整个文档或某个（些）页面提供背景图（也可以是纯色）。
    ///           同时用于为每种部件设置默认配色方案。
    /// </summary>
    public partial class DocumentOptionsDialog : Window
    {
        #region 构造方法=====================================================================================================

        /// <summary>
        /// [构造方法]用以配置文档的背景色（或背景图）。
        /// 
        /// ——由于更改背景色后，可能造成部件选定框或文本不可见。
        ///     因此，允许用户更改默认的文本色与部件选定框的色彩。
        /// </summary>
        /// <param name="masterEditorManager">要使用本配置框的EditorManager。</param>
        public DocumentOptionsDialog(EditorManager masterEditorManager)
        {
            InitializeComponent();

            this.Owner = Globals.MainWindow;
            this.masterEditorManager = masterEditorManager;

            //利用反射取出Brushe类支持的所有色彩，填充到色彩选定框中。
            Type type = typeof(Brushes);
            PropertyInfo[] properties = type.GetProperties();
            foreach (PropertyInfo pi in properties)
            {
                BrushItem bi1 = new BrushItem(pi.GetValue(null, null) as Brush, pi.Name);
                cboxBackgroundBrushes.Items.Add(bi1);

                //BrushItem bi2 = new BrushItem(pi.GetValue(null, null) as Brush, pi.Name);
                //cboxForegroundBrushes.Items.Add(bi2);

                BrushItem bi3 = new BrushItem(pi.GetValue(null, null) as Brush, pi.Name);
                cboxSelBox1Brushes.Items.Add(bi3);

                BrushItem bi4 = new BrushItem(pi.GetValue(null, null) as Brush, pi.Name);
                cboxStartCtrlBrushes.Items.Add(bi4);

                BrushItem bi5 = new BrushItem(pi.GetValue(null, null) as Brush, pi.Name);
                cboxCenterCtrlBrushes.Items.Add(bi5);

                BrushItem bi6 = new BrushItem(pi.GetValue(null, null) as Brush, pi.Name);
                cboxEndCtrlBrushes.Items.Add(bi6);

                BrushItem bi7 = new BrushItem(pi.GetValue(null, null) as Brush, pi.Name);
                CBoxWidgetBackColor.Items.Add(bi7);

                BrushItem bi8 = new BrushItem(pi.GetValue(null, null) as Brush, pi.Name);
                CBoxWidgetLineColor.Items.Add(bi8);

                BrushItem bi9 = new BrushItem(pi.GetValue(null, null) as Brush, pi.Name);
                CBoxWidgetForeColor.Items.Add(bi9);
            }

            if (masterEditorManager != null)
            {
                //SampleLine.Stroke =
                //tbForegroundSample.Foreground = masterEditorManager.DefaultForeground;

                //读入当前文档相关设置
                rect1.Stroke =
                    rect11.Fill = rect11.Stroke =
                    rect12.Fill = rect12.Stroke =
                    rect13.Fill = rect13.Stroke =
                    rect14.Fill = rect14.Stroke =
                    masterEditorManager.WidgetSelectionAdornerBrush;

                EllipseStartCtrl.Fill = masterEditorManager.WidgetStartControlerBrush;
                EllipseCenterCtrl.Fill = masterEditorManager.WidgetCenterControlerBrush;
                EllipseEndCtrl.Fill = masterEditorManager.WidgetEndControlerBrush;
                //示例线的色彩由折线样式决定，返回第一页时没有做更新（没什么必要）。
                //SampleLine.Fill = SampleLine.Stroke = PolyLineStyleSample.MainStyle.WidgetLineColor;

                //如果背景色是纯色，读入背景色，如果不是纯色，读入图像背景。
                switch (masterEditorManager.DefaultBackTileMode)
                {
                    case TileMode.FlipX: { rbtnFlipX.IsChecked = true; break; }
                    case TileMode.FlipXY: { rbtnFlipXY.IsChecked = true; break; }
                    case TileMode.FlipY: { rbtnFlipY.IsChecked = true; break; }
                    case TileMode.Tile: { rbtnTileWithoutFlip.IsChecked = true; break; }
                    case TileMode.None: { rbtnFlipNone.IsChecked = true; break; }
                }

                ImageBrush editorImgBrush = masterEditorManager.DocumentBackground as ImageBrush;
                if (editorImgBrush != null)
                {
                    rectanglePreview.Fill = editorImgBrush;
                    btnResetBackImgBrush.Tag = editorImgBrush;//以便恢复。

                    cboxBackgroundBrushes.IsEnabled = false;
                    dPanelOfImagePath.IsEnabled = true;
                    gpOfImageFlipType.IsEnabled = true;

                    rbtnFillWithImageBrush.IsChecked = true;
                }
                else
                {
                    rbtnFlipXY.IsChecked = true;//默认为水平、垂直翻转并平铺。

                    rbtnFillWithSolidBrush.IsChecked = true;
                    cboxBackgroundBrushes.IsEnabled = true;

                    dPanelOfImagePath.IsEnabled = false;
                    gpOfImageFlipType.IsEnabled = false;

                    rectanglePreview.Fill = masterEditorManager.DocumentBackground;
                    btnResetBackImgBrush.Tag = null;

                    rbtnFillWithSolidBrush.IsChecked = true;
                }

                #region 初始化WidgetStyleSamples

                Thickness margin = new Thickness(20, 10, 20, 10);

                textAreaSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.TextArea).Name) as _WSSTextArea;
                rbtnTextAreaSample = new RadioButton()
                {
                    Content = textAreaSample,
                    IsChecked = true,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };//只选定一个。
                rbtnTextAreaSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnTextAreaSample);
                textAreaSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.TextArea).Name));

                pictureBoxSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.PictureBox).Name) as _WSSPictureBox;
                rbtnPictureBoxSample = new RadioButton()
                {
                    Content = pictureBoxSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnPictureBoxSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnPictureBoxSample);
                pictureBoxSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.PictureBox).Name));

                groupSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.GroupWidget).Name) as _WSSGroupWidget;
                rbtnGroupSample = new RadioButton()
                {
                    Content = groupSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnGroupSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnGroupSample);
                groupSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.GroupWidget).Name));//ContentWidgets

                straitLineSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.StraitLineWidget).Name) as _WSSStraitLineWidget;
                rbtnStraitLineSample = new RadioButton()
                {
                    Content = straitLineSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnStraitLineSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnStraitLineSample);
                straitLineSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.StraitLineWidget).Name));

                bezierLineStyleSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.BezierLineWidget).Name) as _WSSBezierLineWidget;
                rbtnBezierLineStyleSample = new RadioButton()
                {
                    Content = bezierLineStyleSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnBezierLineStyleSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnBezierLineStyleSample);
                bezierLineStyleSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.BezierLineWidget).Name));

                polyLineSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.PolyLineWidget).Name) as _WSSPolyLineWidget;
                rbtnPolyLineSample = new RadioButton()
                {
                    Content = polyLineSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnPolyLineSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnPolyLineSample);
                polyLineSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.PolyLineWidget).Name));

                //示例线的色彩由折线样式决定
                SampleLine.Fill = SampleLine.Stroke = polyLineSample.MainStyle.WidgetLineColor;

                bracketStyleSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.BracketWidget).Name) as _WSSBracketWidget;
                rbtnBracketStyleSample = new RadioButton()
                {
                    Content = bracketStyleSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnBracketStyleSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnBracketStyleSample);
                bracketStyleSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.BracketWidget).Name));//ArrowLineWidgets

                ellipseSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.EllipseWidget).Name) as _WSSEllipseWidget;
                rbtnEllipseSample = new RadioButton()
                {
                    Content = ellipseSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnEllipseSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnEllipseSample);
                ellipseSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.EllipseWidget).Name));

                rectangleSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.RectangleWidget).Name) as _WSSRectangleWidget;
                rbtnRectangleSample = new RadioButton()
                {
                    Content = rectangleSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnRectangleSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnRectangleSample);
                rectangleSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.RectangleWidget).Name));

                rhombSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.RhombWidget).Name) as _WSSRhombWidget;
                rbtnRhombSample = new RadioButton()
                {
                    Content = rhombSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnRhombSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnRhombSample);
                rhombSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.RhombWidget).Name));

                triangleSample = WidgetStyleSample.FromWidgetClassName(
                    typeof(Widgets.TriangleWidget).Name) as _WSSTriangleWidget;
                rbtnTriangleSample = new RadioButton()
                {
                    Content = triangleSample,
                    Margin = margin,
                    Background = Brushes.Transparent,
                };
                rbtnTriangleSample.Checked += new RoutedEventHandler(rbtnSample_Checked);
                mainWrapPanel.Children.Add(rbtnTriangleSample);
                triangleSample.MainStyle.CopyValue(
                    Globals.MainWindow.EditorManager.GetDefaultWidgetStyle(typeof(Widgets.TriangleWidget).Name));//ShapeWidgets

                #endregion

                //为避免不必要的事件，直到此时才挂接。
                //cboxForegroundBrushes.SelectionChanged += new SelectionChangedEventHandler(cboxForegroundBrushes_SelectionChanged);
                rbtnFillWithSolidBrush.Checked += new RoutedEventHandler(rbtnFillWithSolidBrush_Checked);
                cboxBackgroundBrushes.SelectionChanged += new SelectionChangedEventHandler(cboxBackgroundBrushes_SelectionChanged);
                rbtnFillWithImageBrush.Checked += new RoutedEventHandler(rbtnFillWithImageBrush_Checked);

                rbtnFlipX.Checked += new RoutedEventHandler(rbtnFlipX_Checked);
                rbtnFlipY.Checked += new RoutedEventHandler(rbtnFlipY_Checked);
                rbtnFlipXY.Checked += new RoutedEventHandler(rbtnFlipXY_Checked);
                rbtnTileWithoutFlip.Checked += new RoutedEventHandler(rbtnTileWithoutFlip_Checked);
                rbtnFlipNone.Checked += new RoutedEventHandler(rbtnFlipNone_Checked);

                cboxSelBox1Brushes.SelectionChanged += new SelectionChangedEventHandler(cboxSelBox1Brushes_SelectionChanged);
                cboxStartCtrlBrushes.SelectionChanged += new SelectionChangedEventHandler(cboxStartCtrlBrushes_SelectionChanged);
                cboxCenterCtrlBrushes.SelectionChanged += new SelectionChangedEventHandler(cboxCenterCtrlBrushes_SelectionChanged);
                cboxEndCtrlBrushes.SelectionChanged += new SelectionChangedEventHandler(cboxEndCtrlBrushes_SelectionChanged);

                //与默认部件样式相关的事件。
                //注意此处几个事件均需要依赖unableSettingWidgetStyle的值。
                CBoxArrows.SelectionChanged += new SelectionChangedEventHandler(CBoxArrows_SelectionChanged);

                CBoxWidgetBackColor.SelectionChanged += new SelectionChangedEventHandler(CBoxWidgetBackColor_SelectionChanged);
                CBoxWidgetLineColor.SelectionChanged += new SelectionChangedEventHandler(CBoxWidgetLineColor_SelectionChanged);
                CBoxWidgetForeColor.SelectionChanged += new SelectionChangedEventHandler(CBoxWidgetForeColor_SelectionChanged);

                CBoxWidgetLineWidth.SelectionChanged += new SelectionChangedEventHandler(CBoxWidgetLineWidth_SelectionChanged);
                CBoxWidgetLineDash.SelectionChanged += new SelectionChangedEventHandler(CBoxWidgetLineDash_SelectionChanged);
                CBoxIsShadowVisible.SelectionChanged += new SelectionChangedEventHandler(CBoxIsShadowVisible_SelectionChanged);

                SDOpacity.ValueChanged += new RoutedPropertyChangedEventHandler<double>(SDOpacity_ValueChanged);
                SDPadding.ValueChanged += new RoutedPropertyChangedEventHandler<double>(SDPadding_ValueChanged);

                SDRadius.ValueChanged += new RoutedPropertyChangedEventHandler<double>(SDRadius_ValueChanged);
            }
        }

        void rbtnSample_Checked(object sender, RoutedEventArgs e)
        {
            this.unableSettingWidgetStyle = true;

            CBoxArrows.SelectedIndex =
                CBoxWidgetBackColor.SelectedIndex =
                CBoxWidgetLineColor.SelectedIndex =
                CBoxWidgetForeColor.SelectedIndex =
                CBoxWidgetLineDash.SelectedIndex =
                CBoxWidgetLineWidth.SelectedIndex =
                CBoxIsShadowVisible.SelectedIndex = -1;
            SDOpacity.Value = 1;
            SDPadding.Value = 0;

            this.unableSettingWidgetStyle = false;//返回.
        }

        /// <summary>
        /// 在切换到另一个部件样式时，将此值改为真，以避免不需要的事件效果。
        /// </summary>
        private bool unableSettingWidgetStyle = false;

        void CBoxArrows_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;
            ComboBoxItem item = CBoxArrows.SelectedItem as ComboBoxItem;
            if (item == null) return;

            string tag = item.Tag.ToString();

            widgetStyle.Arrows = (Enums.ArrowType)Enum.Parse(typeof(Enums.ArrowType), tag);
        }

        void CBoxIsShadowVisible_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;

            ComboBoxItem item = CBoxIsShadowVisible.SelectedItem as ComboBoxItem;
            if (item == null) return;

            string tag = item.Tag.ToString();
            if (tag == "True")
            {
                widgetStyle.IsShadowVisible = true;
            }
            else// if (tag == "False")
            {
                widgetStyle.IsShadowVisible = false;
            }
        }

        void CBoxWidgetLineDash_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;

            widgetStyle.LineDash = (LineDashType.DashType)Enum.Parse(typeof(LineDashType.DashType),
                (CBoxWidgetLineDash.SelectedItem as ComboBoxItem).Tag.ToString());
        }

        private WidgetStyle GetSelectedWidgetStyle()
        {
            if (mainWrapPanel == null) return null;

            foreach (UIElement ue in mainWrapPanel.Children)
            {
                RadioButton rBtn = ue as RadioButton;
                if (rBtn == null) continue;

                if (rBtn.IsChecked == true)
                {
                    WidgetStyleSample styleSample = rBtn.Content as WidgetStyleSample;
                    if (styleSample != null)
                    {
                        return styleSample.MainStyle;//理论上可能为null。实际上不会。
                    }
                }
            }

            return null;
        }

        void CBoxWidgetLineWidth_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;

            widgetStyle.WidgetLineWidth =
                double.Parse((CBoxWidgetLineWidth.SelectedItem as ComboBoxItem).Tag.ToString());
        }

        void CBoxWidgetForeColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;

            widgetStyle.WidgetForeColor =
                BrushManager.GetBrush((CBoxWidgetForeColor.SelectedItem as BrushItem).BrushName);
        }

        void CBoxWidgetLineColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;

            widgetStyle.WidgetLineColor =
                BrushManager.GetBrush((CBoxWidgetLineColor.SelectedItem as BrushItem).BrushName);
        }

        void CBoxWidgetBackColor_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;

            widgetStyle.WidgetBackColor =
                BrushManager.GetBrush((CBoxWidgetBackColor.SelectedItem as BrushItem).BrushName);
        }

        void cboxEndCtrlBrushes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //线型部件控制点色彩
            BrushItem bi = cboxEndCtrlBrushes.SelectedItem as BrushItem;

            if (bi != null)
            {
                Brush bsh = bi.Bsh;

                EllipseEndCtrl.Fill = bsh;
            }
            else
            {
                if (masterEditorManager != null)
                {
                    Brush bsh = masterEditorManager.WidgetEndControlerBrush;

                    EllipseEndCtrl.Fill = bsh;
                }
            }
        }

        void cboxCenterCtrlBrushes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //线型部件控制点色彩
            BrushItem bi = cboxCenterCtrlBrushes.SelectedItem as BrushItem;

            if (bi != null)
            {
                Brush bsh = bi.Bsh;

                EllipseCenterCtrl.Fill = bsh;
            }
            else
            {
                if (masterEditorManager != null)
                {
                    Brush bsh = masterEditorManager.WidgetCenterControlerBrush;

                    EllipseCenterCtrl.Fill = bsh;
                }
            }
        }

        void cboxStartCtrlBrushes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //线型部件控制点色彩
            BrushItem bi = cboxStartCtrlBrushes.SelectedItem as BrushItem;

            if (bi != null)
            {
                Brush bsh = bi.Bsh;

                EllipseStartCtrl.Fill = bsh;
            }
            else
            {
                if (masterEditorManager != null)
                {
                    Brush bsh = masterEditorManager.WidgetSelectionAdornerBrush;

                    EllipseStartCtrl.Fill = bsh;
                }
            }
        }


        #endregion


        #region 字段与属性===================================================================================================

        /// <summary>
        /// 使用此对话框的EditorManager。
        /// </summary>
        private EditorManager masterEditorManager;

        #endregion


        #region 关于WidgetStyleSample的相关字段、属性

        private _WSSBezierLineWidget bezierLineStyleSample;

        private _WSSBracketWidget bracketStyleSample;

        private _WSSEllipseWidget ellipseSample;

        private _WSSGroupWidget groupSample;

        private _WSSPictureBox pictureBoxSample;

        private _WSSPolyLineWidget polyLineSample;

        private _WSSRectangleWidget rectangleSample;

        private _WSSRhombWidget rhombSample;

        private _WSSStraitLineWidget straitLineSample;

        private _WSSTextArea textAreaSample;

        private _WSSTriangleWidget triangleSample;

        //下面是对应的用于封装Styles的CheckBox
        private RadioButton rbtnBezierLineStyleSample;

        private RadioButton rbtnBracketStyleSample;

        private RadioButton rbtnEllipseSample;

        private RadioButton rbtnGroupSample;

        private RadioButton rbtnPictureBoxSample;

        private RadioButton rbtnPolyLineSample;

        private RadioButton rbtnRectangleSample;

        private RadioButton rbtnRhombSample;

        private RadioButton rbtnStraitLineSample;

        private RadioButton rbtnTextAreaSample;

        private RadioButton rbtnTriangleSample;
        #endregion

        #region 方法=========================================================================================================

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close();
        }

        private void btnBrowseImageFile_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Multiselect = false;
            ofd.Title = Globals.AppName + "——请为文档选择需要的背景图片：";
            ofd.Filter = "支持的所有图片格式(*.bmp;*.gif;*.jpg;*.jpeg;*.png;*.tiff)|*.bmp;*.gif;*.jpg;*.jpeg;*.png;*.tiff|" +
                "PNG或JPEG图片(*.png;*.jpg;*.jpeg)|*.png;*.jpg;*.jpeg|" +
                "联合图像专家组格式(*.jpg;*.jpeg)|*.jpg;*.jpeg|" +
                "图形交换格式(*.gif)|*.gif|" +
                "W3C 可移植网络图形(*png)|*png|" +
                "标题图像文件(*.tiff)|*.tiff";

            if (ofd.ShowDialog() != true) return;

            string filename = ofd.FileName;

            ImageBrush newBrush;

            TileMode mode;
            mode = GetTileMode();

            string result = BrushManager.ParseToText(filename, out newBrush, mode);

            rectanglePreview.Fill = newBrush;

            tbxImageFilePath.Tag = result;
        }

        /// <summary>
        /// 根据哪个按钮被选定判断用户决定用哪种TileMode。
        /// </summary>
        private TileMode GetTileMode()
        {
            TileMode mode;
            if (rbtnFlipX.IsChecked == true)
            {
                mode = TileMode.FlipX;
            }
            else if (rbtnFlipY.IsChecked == true)
            {
                mode = TileMode.FlipY;
            }
            else if (rbtnFlipXY.IsChecked == true)
            {
                mode = TileMode.FlipXY;
            }
            else if (rbtnTileWithoutFlip.IsChecked == true)
            {
                mode = TileMode.Tile;
            }
            else //if (rbtnFlipNone.IsChecked == true)
            {
                mode = TileMode.None;
            }
            return mode;
        }

        private void btnOK_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();

            ModifingInfo info = new ModifingInfo();
            info.ModifingDescription = "文档特性设置";
            masterEditorManager.GetSelectedPageEditorStatus(info);
            masterEditorManager.GetSelectedWidgetStatus_Old(info);
            masterEditorManager.GetSelectedWidgetStatus_New(info);

            ModifingItem<Action, ModifingInfo> mi = new ModifingItem<Action, ModifingInfo>(info);

            //Brush oldForeground = masterEditorManager.DefaultForeground;

            //Brush newForeground = tbForegroundSample.Foreground;
            Brush newBackground = rectanglePreview.Fill;
            Brush newSelboxBrush = rect1.Stroke;
            Brush newStartCtrlBrush = EllipseStartCtrl.Fill;
            Brush newCenterCtrlBrush = EllipseCenterCtrl.Fill;
            Brush newEndCtrlBrush = EllipseEndCtrl.Fill;

            //写入文档背景
            TileMode newTileMode = this.GetTileMode();
            if (newTileMode != masterEditorManager.DefaultBackTileMode)
            {
                Action actTileMode = new Action(ActionType.TileMode,
                    masterEditorManager.DefaultBackTileMode.ToString(),
                    newTileMode.ToString());

                masterEditorManager.DefaultBackTileMode = newTileMode;

                mi.AddAction(actTileMode);
            }

            if (rbtnFillWithImageBrush.IsChecked == true)
            {
                if (newBackground != masterEditorManager.DocumentBackground)
                {
                    string oldBrushValue = masterEditorManager.DocumentBackgroundText;
                    ImageBrush newImageBrush = rectanglePreview.Fill as ImageBrush;
                    if (newImageBrush != null)
                    {
                        //将图片生成的base64文本写入editor。
                        string base64Str = tbxImageFilePath.Tag as string;
                        if (base64Str != null)
                        {
                            Action actBackground = new Action(ActionType.DefaultBackgroundChanged,
                                oldBrushValue, base64Str);

                            masterEditorManager.DocumentBackgroundText = base64Str;
                            mi.AddAction(actBackground);
                        }
                    }
                }
            }
            else if (rbtnFillWithSolidBrush.IsChecked == true)
            {
                if (cboxBackgroundBrushes.SelectedIndex > 0)
                {
                    Brush newSolidBackBrush = rectanglePreview.Fill as SolidColorBrush;

                    if (newSolidBackBrush != null)
                    {
                        Action actBackground = new Action(ActionType.DefaultBackgroundChanged,
                                masterEditorManager.DocumentBackgroundText, BrushManager.ParseToText(newBackground));

                        masterEditorManager.DocumentBackgroundText = BrushManager.ParseToText(newSolidBackBrush);
                        mi.AddAction(actBackground);
                    }
                }

            }

            //写入“部件选定框色”。
            if (newSelboxBrush != masterEditorManager.WidgetSelectionAdornerBrush)
            {
                Action actSelColor = new Action(ActionType.WidgetSelectionAdornerBrushChanged,
                    BrushManager.GetName(masterEditorManager.WidgetSelectionAdornerBrush),
                    BrushManager.GetName(newSelboxBrush));

                masterEditorManager.WidgetSelectionAdornerBrush = newSelboxBrush;
                mi.AddAction(actSelColor);
            }

            //写入“首控制点色”。
            if (newStartCtrlBrush != masterEditorManager.WidgetStartControlerBrush)
            {
                Action actStartCtrl = new Action(ActionType.WidgetStartCtrlBrushChanged,
                    BrushManager.GetName(masterEditorManager.WidgetStartControlerBrush),
                    BrushManager.GetName(newStartCtrlBrush));

                masterEditorManager.WidgetStartControlerBrush = newStartCtrlBrush;
                mi.AddAction(actStartCtrl);
            }


            //写入“中控制点色”。
            if (newCenterCtrlBrush != masterEditorManager.WidgetCenterControlerBrush)
            {
                Action actCenterCtrl = new Action(ActionType.WidgetCenterCtrlBrushChanged,
                    BrushManager.GetName(masterEditorManager.WidgetCenterControlerBrush),
                    BrushManager.GetName(newCenterCtrlBrush));

                masterEditorManager.WidgetCenterControlerBrush = newCenterCtrlBrush;
                mi.AddAction(actCenterCtrl);
            }

            //写入“尾控制点色”。
            if (newEndCtrlBrush != masterEditorManager.WidgetEndControlerBrush)
            {
                Action actEndCtrl = new Action(ActionType.WidgetEndCtrlBrushChanged,
                    BrushManager.GetName(masterEditorManager.WidgetEndControlerBrush),
                    BrushManager.GetName(newEndCtrlBrush));

                masterEditorManager.WidgetEndControlerBrush = newEndCtrlBrush;
                mi.AddAction(actEndCtrl);
            }

            //2012年6月20日设置文档中各部件的“默认样式”

            WidgetStyle s1 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.TextArea).Name);
            WidgetStyle ns1 = textAreaSample.MainStyle;
            if (s1 != null && ns1 != null)
            {
                Action act1 = new Action(ActionType.SetWidgetStyle,
                    s1.ToString(), ns1.ToString());
                masterEditorManager.SetWidgetStyle(ns1);
                mi.AddAction(act1);
            }

            WidgetStyle s2 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.PictureBox).Name);
            WidgetStyle ns2 = pictureBoxSample.MainStyle;
            if (s2 != null && ns2 != null)
            {
                Action act2 = new Action(ActionType.SetWidgetStyle,
                    s2.ToString(), ns2.ToString());
                masterEditorManager.SetWidgetStyle(ns2);
                mi.AddAction(act2);
            }

            WidgetStyle s3 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.GroupWidget).Name);
            WidgetStyle ns3 = groupSample.MainStyle;
            if (s3 != null && ns3 != null)
            {
                Action act3 = new Action(ActionType.SetWidgetStyle,
                    s3.ToString(), ns3.ToString());
                masterEditorManager.SetWidgetStyle(ns3);
                mi.AddAction(act3);
            }

            WidgetStyle s4 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.StraitLineWidget).Name);
            WidgetStyle ns4 = straitLineSample.MainStyle;
            if (s4 != null && ns4 != null)
            {
                Action act4 = new Action(ActionType.SetWidgetStyle,
                    s4.ToString(), ns4.ToString());
                masterEditorManager.SetWidgetStyle(ns4);
                mi.AddAction(act4);
            }

            WidgetStyle s5 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.BezierLineWidget).Name);
            WidgetStyle ns5 = bezierLineStyleSample.MainStyle;
            if (s5 != null && ns5 != null)
            {
                Action act5 = new Action(ActionType.SetWidgetStyle,
                    s5.ToString(), ns5.ToString());
                masterEditorManager.SetWidgetStyle(ns5);
                mi.AddAction(act5);
            }

            WidgetStyle s6 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.PolyLineWidget).Name);
            WidgetStyle ns6 = polyLineSample.MainStyle;
            if (s6 != null && ns6 != null)
            {
                Action act6 = new Action(ActionType.SetWidgetStyle,
                    s6.ToString(), ns6.ToString());
                masterEditorManager.SetWidgetStyle(ns6);
                mi.AddAction(act6);
            }

            WidgetStyle s7 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.BracketWidget).Name);
            WidgetStyle ns7 = bracketStyleSample.MainStyle;
            if (s7 != null && ns7 != null)
            {
                Action act7 = new Action(ActionType.SetWidgetStyle,
                    s7.ToString(), ns7.ToString());
                masterEditorManager.SetWidgetStyle(ns7);
                mi.AddAction(act7);
            }

            WidgetStyle s8 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.EllipseWidget).Name);
            WidgetStyle ns8 = ellipseSample.MainStyle;
            if (s8 != null && ns8 != null)
            {
                Action act8 = new Action(ActionType.SetWidgetStyle,
                    s8.ToString(), ns8.ToString());
                masterEditorManager.SetWidgetStyle(ns8);
                mi.AddAction(act8);
            }

            WidgetStyle s9 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.RectangleWidget).Name);
            WidgetStyle ns9 = rectangleSample.MainStyle;
            if (s9 != null && ns9 != null)
            {
                Action act9 = new Action(ActionType.SetWidgetStyle,
                    s9.ToString(), ns9.ToString());
                masterEditorManager.SetWidgetStyle(ns9);
                mi.AddAction(act9);
            }

            WidgetStyle s10 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.RhombWidget).Name);
            WidgetStyle ns10 = rhombSample.MainStyle;
            if (s10 != null && ns10 != null)
            {
                Action act10 = new Action(ActionType.SetWidgetStyle,
                    s10.ToString(), ns10.ToString());
                masterEditorManager.SetWidgetStyle(ns10);
                mi.AddAction(act10);
            }

            WidgetStyle s11 = masterEditorManager.GetDefaultWidgetStyle(typeof(Widgets.TriangleWidget).Name);
            WidgetStyle ns11 = triangleSample.MainStyle;
            if (s11 != null && ns11 != null)
            {
                Action act11 = new Action(ActionType.SetWidgetStyle,
                    s11.ToString(), ns11.ToString());
                masterEditorManager.SetWidgetStyle(ns11);
                mi.AddAction(act11);
            }

            //最后，检查部件是否前景色与默认背景色相同，且部件背景色为透明，如果相同，强行改为新前景色。
            //foreach (UIElement uePage in masterEditorManager.Children)
            //{
            //    PageEditor pe = uePage as PageEditor;
            //    if (pe == null) continue;

            //    foreach (UIElement ueWidget in pe.Children)
            //    {
            //        Widgets.Widget w = ueWidget as Widgets.Widget;
            //        if (w == null) continue;

            //        if (w.WidgetForeColor == newBackground)//如果是图片背景，总是为否！！！
            //        {
            //            if (w is Widgets.ArrowLineWidget)
            //            {
            //                //线型无论背景如何，均更改前景为新的页面前景
            //                Action actWidgetForeColor = new Action(pe.Id, w.Id, w.GetType().Name, XmlTags.WidgetForeColor,
            //                BrushManager.GetName(w.WidgetForeColor), BrushManager.GetName(newForeground));
            //                w.WidgetForeColor = newForeground;
            //                mi.AddAction(actWidgetForeColor);

            //                //这里与字符串命令不同：字符串命令只能设置为非图像背景。
            //                //如果是图片背景，则线型部件背景作透明处理。

            //                //如果是图片背景，根本不会执行到此处！！！
            //                Action actWidgetBackColor = new Action(pe.Id, w.Id, w.GetType().Name, XmlTags.WidgetBackColor,
            //                    BrushManager.GetName(w.WidgetBackColor), BrushManager.GetName(newBackground));
            //                w.WidgetBackColor = newBackground;
            //                mi.AddAction(actWidgetBackColor);
            //            }
            //            else
            //            {
            //                //其它部件，只有部件背景是透明或部件背景也等于页面背景时才有必要更改部件前景为新的页面前景。
            //                if (w.WidgetBackColor == Brushes.Transparent || w.WidgetForeColor == newBackground)
            //                {
            //                    Action actWidgetForeColor = new Action(pe.Id, w.Id, w.GetType().Name, XmlTags.WidgetForeColor,
            //                        BrushManager.GetName(w.WidgetForeColor), BrushManager.GetName(newForeground));
            //                    w.WidgetForeColor = newForeground;
            //                    mi.AddAction(actWidgetForeColor);
            //                }
            //            }
            //        }
            //else
            //{
            //    if (w.WidgetForeColor == oldForeground)
            //    {
            //        Action actWidgetForeColor = new Action(pe.Id, w.Id, w.GetType().Name, XmlTags.WidgetForeColor,
            //        BrushManager.GetName(w.WidgetForeColor), BrushManager.GetName(newForeground));
            //        w.WidgetForeColor = newForeground;
            //        mi.AddAction(actWidgetForeColor);

            //        Brush tmpBrush = (newBackground is SolidColorBrush ? newBackground : Brushes.Transparent);
            //        //无法确定图像背景的色调，只得设为透明。

            //        Action actWidgetBackColor = new Action(pe.Id, w.Id, w.GetType().Name, XmlTags.WidgetBackColor,
            //            BrushManager.GetName(w.WidgetBackColor), BrushManager.GetName(tmpBrush));
            //        w.WidgetBackColor = tmpBrush;
            //        mi.AddAction(actWidgetBackColor);
            //    }
            //}
            //    }
            //}

            masterEditorManager.RegisterModifingItem(mi);
        }

        /// <summary>
        /// 图像背景复位按钮。
        /// </summary>
        private void btnResetBackImgBrush_Click(object sender, RoutedEventArgs e)
        {
            if (btnResetBackImgBrush.Tag == null)
            {
                MessageBox.Show("　　此文档的背景不是图片，不能复位。", Globals.AppName,
                    MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            ImageBrush ibsh = btnResetBackImgBrush.Tag as ImageBrush;
            if (ibsh != null)
            {
                rectanglePreview.Fill = ibsh;
            }
        }

        private void cboxBackgroundBrushes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            BrushItem bi = cboxBackgroundBrushes.SelectedItem as BrushItem;
            if (bi != null)
            {
                rectanglePreview.Fill = bi.Bsh;
            }
            else
            {
                if (masterEditorManager != null)
                {
                    rectanglePreview.Fill = masterEditorManager.DocumentBackground;
                }
            }
        }

        //private void cboxForegroundBrushes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        //{
        //    BrushItem bi = cboxForegroundBrushes.SelectedItem as BrushItem;
        //    if (bi != null)
        //    {
        //        SampleLine.Stroke =
        //           tbForegroundSample.Foreground = bi.Bsh;
        //    }
        //    else
        //    {
        //        if (masterEditorManager != null)
        //        {
        //            SampleLine.Stroke =
        //               tbForegroundSample.Foreground = masterEditorManager.DefaultForeground;
        //        }
        //    }
        //}

        private void cboxSelBox1Brushes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            //普通公式的选定框色
            BrushItem bi = cboxSelBox1Brushes.SelectedItem as BrushItem;

            if (bi != null)
            {
                Brush bsh = bi.Bsh;

                rect1.Stroke = bsh;
                rect11.Fill = bsh;
                rect12.Fill = bsh;
                rect13.Fill = bsh;
                rect14.Fill = bsh;
            }
            else
            {
                if (masterEditorManager != null)
                {
                    Brush bsh = masterEditorManager.WidgetSelectionAdornerBrush;

                    rect1.Stroke = bsh;
                    rect11.Fill = bsh;
                    rect12.Fill = bsh;
                    rect13.Fill = bsh;
                    rect14.Fill = bsh;
                }
            }
        }

        void rbtnFlipNone_Checked(object sender, RoutedEventArgs e)
        {
            ImageBrush ibsh = rectanglePreview.Fill as ImageBrush;
            if (ibsh != null)
            {
                ibsh.TileMode = TileMode.None;
            }
        }

        void rbtnFlipX_Checked(object sender, RoutedEventArgs e)
        {
            ImageBrush ibsh = rectanglePreview.Fill as ImageBrush;
            if (ibsh != null)
            {
                ibsh.TileMode = TileMode.FlipX;
            }
        }

        void rbtnFlipXY_Checked(object sender, RoutedEventArgs e)
        {
            ImageBrush ibsh = rectanglePreview.Fill as ImageBrush;
            if (ibsh != null)
            {
                ibsh.TileMode = TileMode.FlipXY;
            }
        }

        void rbtnFlipY_Checked(object sender, RoutedEventArgs e)
        {
            ImageBrush ibsh = rectanglePreview.Fill as ImageBrush;
            if (ibsh != null)
            {
                ibsh.TileMode = TileMode.FlipY;
            }
        }

        void rbtnTileWithoutFlip_Checked(object sender, RoutedEventArgs e)
        {
            ImageBrush ibsh = rectanglePreview.Fill as ImageBrush;
            if (ibsh != null)
            {
                ibsh.TileMode = TileMode.Tile;
            }
        }

        private void rbtnFillWithSolidBrush_Checked(object sender, RoutedEventArgs e)
        {
            if (dPanelOfImagePath != null) dPanelOfImagePath.IsEnabled = false;
            if (gpOfImageFlipType != null) gpOfImageFlipType.IsEnabled = false;
            if (cboxBackgroundBrushes != null) cboxBackgroundBrushes.IsEnabled = true;
        }

        private void rbtnFillWithImageBrush_Checked(object sender, RoutedEventArgs e)
        {
            if (dPanelOfImagePath != null) dPanelOfImagePath.IsEnabled = true;
            if (gpOfImageFlipType != null) gpOfImageFlipType.IsEnabled = true;
            if (cboxBackgroundBrushes != null) cboxBackgroundBrushes.IsEnabled = false;
        }

        #endregion


        #region 其它=========================================================================================================

        /// <summary>
        /// 用于填充色彩选定框的Item类。
        /// </summary>
        internal class BrushItem : ComboBoxItem
        {
            static Thickness ItemMargin = new Thickness(10, 0, 10, 0);

            public BrushItem(Brush bsh, string bshName)
            {
                Bsh = bsh;
                BrushName = bshName;

                StackPanel sPanel = new StackPanel() { Orientation = Orientation.Horizontal };
                this.Content = sPanel;

                sPanel.Children.Add(new Rectangle() { Width = 10, Height = 10, Fill = bsh });
                sPanel.Children.Add(new TextBlock() { Text = ToString(), Margin = ItemMargin });
            }

            public Brush Bsh { get; set; }

            public string BrushName { get; set; }

            public override string ToString()
            {
                return BrushName;
            }
        }

        #endregion

        private void btnPreview_Click(object sender, RoutedEventArgs e)
        {
            if (MainTabControl.SelectedIndex > 0)
            {
                MainTabControl.SelectedIndex -= 1;
            }

            if (MainTabControl.SelectedIndex <= 0)
            {
                btnPreview.IsEnabled = false;
            }

            if (MainTabControl.SelectedIndex < MainTabControl.Items.Count - 1)
            {
                btnNext.IsEnabled = true;
            }
        }

        private void btnNext_Click(object sender, RoutedEventArgs e)
        {
            if (MainTabControl.SelectedIndex < MainTabControl.Items.Count - 1)
            {
                MainTabControl.SelectedIndex += 1;
            }

            if (MainTabControl.SelectedIndex >= MainTabControl.Items.Count - 1)
            {
                btnNext.IsEnabled = false;
            }

            if (MainTabControl.SelectedIndex > 0)
            {
                btnPreview.IsEnabled = true;
            }

            mainWrapPanel.Background = rectanglePreview.Fill;
        }

        private void SDPadding_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;

            widgetStyle.WidgetPadding = new Thickness(SDPadding.Value);
        }

        private void SDOpacity_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;

            widgetStyle.WidgetOpacity = SDOpacity.Value;
        }

        void SDRadius_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
        {
            if (this.unableSettingWidgetStyle) return;//只是选定了另一个部件样式示例。

            WidgetStyle widgetStyle = GetSelectedWidgetStyle();
            if (widgetStyle == null) return;

            widgetStyle.Radius = SDRadius.Value;
        }
    }
}
